import { Component, OnInit } from '@angular/core';
import { AuditManageService } from './audit-manage.service';
import { FormGroup, FormBuilder, Validators, FormArray } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { HCommonService } from 'src/app/h-common/h-common.service';

@Component({
    selector: 'app-audit-manage',
    templateUrl: './audit-manage.component.html',
    styleUrls: ['./audit-manage.component.scss']
})
export class AuditManageComponent implements OnInit {
    value: string = "";
    auditCode: string = "";
    auditName: string = "";
    pageIndex: number = 1;
    pageSize: number = 10;
    isShow: boolean = false;
    isOkLoading: boolean = false;
    editId: number = -1;
    listCount: number = 0;
    isAllChecked: boolean = false;
    indeterminate: boolean = false;
    deleteIds = [];
    mapOfCheckedId = {};
    userListData: [];
    levelData = [];
    selectedLevel = [];
    auditForm: FormGroup;
    listData = []
    bornRole = {}

    modalDomBox : any

    constructor(
        private auditService: AuditManageService,
        private fb: FormBuilder,
        private modalService: NzModalService,
        private commonService : HCommonService
    ) { }

    ngOnInit(): void {
        this.modalDomBox = document.querySelector("#modal_box");
        this.bornRole = this.commonService.getRoles("audit");

        this.auditForm = this.fb.group({
            code: [""],
            name: ["", Validators.required],
            level: ["", Validators.required],
            resultUser: [[], Validators.required],
            remark: [""],
            auditUser: this.fb.array([])
        })


        this.getList();
        this.getUserList();
        this.getLevel();
    }
    get auditUserArray() {
        return this.auditForm.get("auditUser") as FormArray
    }
    getLevel() {
        this.auditService.apiLevel("audit_level").subscribe(res => {
            this.levelData = res
        })
    }
    levelChange(level) {
        let _num = Number(level);
        this.auditUserArray.clear();
        for (let i = 0; i < _num; i++) {
            this.auditUserArray.push(this.fb.control(null, Validators.required))
        }
    }
    getList() {
        let _dataJson = {
            id: this.auditCode,
            name: this.auditName,
            page: this.pageIndex,
            size: this.pageSize
        }
        this.auditService.apiList(_dataJson).subscribe(res => {
            this.listData = res.content;
            this.listCount = res.totalElements
        })
    }
    checkAll(status) {
        this.listData.forEach(item => {
            this.mapOfCheckedId[item.id] = status;
        })
        this.indeterminate = false;
    }
    refreshStatus() {
        this.isAllChecked = this.listData.every(item => {
            return this.mapOfCheckedId[item.id]
        })
        this.indeterminate = this.listData.some(item => {
            return this.mapOfCheckedId[item.id] && !this.isAllChecked
        })
        this.filterDelData();
    }
    filterDelData() {
        this.deleteIds = [];
        for (const key in this.mapOfCheckedId) {
            const value = this.mapOfCheckedId[key];
            if (value) {
                this.deleteIds.push(Number(key))
            }
        }
    }
    showModal() {
        this.isShow = true;
        this.editId = -1;
        this.auditForm.reset({
            code: "",
            name: "",
            resultUser: [],
        })
    }
    handleCancel() {
        this.isShow = false;
    }
    submitForm() {
        let _formControls = this.auditForm.controls;
        let _arrayControls = this.auditUserArray.controls;
        for (const i in _formControls) {
            _formControls[i].markAsDirty();
            _formControls[i].updateValueAndValidity();
        }
        for (const i in _arrayControls) {
            _arrayControls[i].markAsDirty();
            _arrayControls[i].updateValueAndValidity();
        }

        let _formValue = this.auditForm.value;
        let _arrayValue = this.auditUserArray.value;
        let _tempArr = []
        _arrayValue.forEach((item, index: number) => {
            item.forEach($item => {
                _tempArr.push({
                    level: (index + 1),
                    userId: $item
                })
            })
        })
        let _dataJson = {
            name: _formValue.name,
            level: _formValue.level,
            auditors: _tempArr,
            cc: _formValue.resultUser.join(","),
            remarks: _formValue.remark
        }
        if (this.editId == -1) {
            this.auditService.apiSave(_dataJson).subscribe(res => {
                this.isShow = false;
                this.initStatus();
            })
        } else {
            let _data = {
                ..._dataJson,
                id: this.editId
            }
            this.auditService.apiEdit(_data).subscribe(res => {
                this.isShow = false;
                this.initStatus();
            })
        }

    }
    initStatus() {
        this.indeterminate = this.isAllChecked = false;
        this.mapOfCheckedId = {};
        this.deleteIds = [];
        this.getList();
    }
    delete() {
        this.modalService.confirm({
            nzTitle: '确定要删除这些数据吗？',
            nzContent: '',
            nzOkText: '确认',
            nzCancelText: '取消',
            nzOnOk: () => {
                this.auditService.apiDelete(this.deleteIds).subscribe(res => {
                    this.initStatus();
                })
            }
        });
    }
    listPageChange(page) {
        this.pageIndex = page;
        this.getList();
    }
    search() {
        this.pageIndex = 1;
        this.getList();
    }
    showEditModal() {
        let _data = this.listData.filter(item => {
            return item.id == this.deleteIds[0]
        })[0];
        this.isShow = true;
        this.editId = _data.id;
        this.levelChange(_data.auditors.length);
        let _tempArr = []
        _data.auditors.forEach(item => {
            _tempArr[item.level - 1] = !_tempArr[item.level - 1] ? [] : _tempArr[item.level - 1];
            _tempArr[item.level - 1] = [..._tempArr[item.level - 1], item.user.id]
        });
        let resultUser = _data.ccList.map(item=>{
            return item.id
        })
        this.auditForm.patchValue({
            name: _data.name,
            level: ""+_data.level,
            auditUser: _tempArr,
            resultUser: resultUser,
            remark: _data.remarks
        })
    }
    getUserList() {
        this.auditService.apiGetUser().subscribe(res => {
            this.userListData = res.content;
        });
    }
}
